package controller

import (
	"gin-demo/common"
	"gin-demo/dto"
	"gin-demo/model"
	"gin-demo/response"
	"gin-demo/util"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
	"log"
	"net/http"
)

func Register(ctx *gin.Context) {
	//DB :=
	DB := common.InitDB()
	defer DB.Close()
	//获取参数
	//name := ctx.PostForm("name")
	//telephone := ctx.PostForm("telephone")
	//password := ctx.PostForm("password")
	var requestMap = model.User{}
	//json.NewDecoder(ctx.Request.Body).Decode(&requestMap)
	ctx.Bind(&requestMap)//gin框架提供的方法绑定数据结构体
	name := requestMap.Name
	telephone := requestMap.Telephone
	password := requestMap.Password
	//数据验证
	if len(telephone) != 11 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "手机号必须为11位")
		//ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"手机号必须为11位"})
		return
	}
	if len(password) < 6 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位")
		//ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"密码不能少于6位"})
		return
	}
	//如果名称有传，给一个10位的随机字符串
	if len(name) == 0 {
		name = util.RandomString(10)
	}
	//判断手机是否存在e
	//log.Println(name,telephone,password)
	if isTelephoneExist(DB, telephone) {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "用户已存在")
		//ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"用户已存在"})
		return
	}

	//创建用户,将密码加密
	hasedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		response.Response(ctx, http.StatusUnprocessableEntity, 500, nil, "加密错误")
		//ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":500,"msg":"加密错误"})
		return
	}
	newUser := model.User{
		Name:      name,
		Telephone: telephone,
		Password:  string(hasedPassword),
	}
	DB.Create(&newUser)
	//发放token
	token, err := common.ReleaseToken(newUser)
	if err != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "系统异常")
		//ctx.JSON(http.StatusInternalServerError,gin.H{"code":500,"msg":"系统异常"})
		log.Println("token generate error:", err)
		return
	}
	//返回结果
	response.Success(ctx, gin.H{"token": token}, "注册成功")
	//ctx.JSON(200, gin.H{
	//		"code":200,
	//		"message": "注册成功",
	//	})
}

func Login(ctx *gin.Context) {
	DB := common.InitDB()
	defer DB.Close()
	//获取参数
	telephone := ctx.PostForm("telephone")
	password := ctx.PostForm("password")
	//数据验证
	if len(telephone) != 11 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "手机号必须为11位")
		//ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"手机号必须为11位"})
		return
	}
	if len(password) < 6 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位")
		//ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"密码不能少于6位"})
		return
	}
	//判断手机号是否存在
	var user model.User
	DB.Where("telephone=?", telephone).First(&user)
	if user.ID == 0 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "用户不存在")
		//ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"用户不存在"})
		return
	}
	//判断密码是否正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "密码错误")
		//ctx.JSON(http.StatusBadRequest,gin.H{"code":400,"msg":"密码错误"})
		return
	}
	//发放token
	token, err := common.ReleaseToken(user)
	if err != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "系统异常")
		//ctx.JSON(http.StatusInternalServerError,gin.H{"code":500,"msg":"系统异常"})
		log.Println("token generate error:", err)
		return
	}
	//返回结果
	response.Success(ctx, gin.H{"token": token}, "登录成功")
	//ctx.JSON(200,gin.H{
	//	"code":200,
	//	"data":gin.H{"token":token},
	//	"msg":"登陆成功",
	//})
}
func Info(ctx *gin.Context) {
	user, err := ctx.Get("user")
	if !err {
		ctx.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "获取用户信息失败"})
		return
	}
	response.Success(ctx, gin.H{"data": dto.ToUserDto(user.(model.User))}, "获取用户信息成功")
	//ctx.JSON(http.StatusOK,gin.H{"code":200,"msg":"获取成功","data":gin.H{"user":dto.ToUserDto(user.(model.User))}})
}
func isTelephoneExist(db *gorm.DB, telephone string) bool {
	var user model.User
	db.Where("telephone=?", telephone).First(&user)

	if user.ID != 0 {
		return true
	}
	return false
}
